package com.programmercarl.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.cn/problems/restore-ip-addresses/description/
 * 复原IP地址
 * @author yulongtian
 * @create 2025-01-10 22:11
 */
public class Test07 {
    public static void main(String[] args) {
        Test07 test07 = new Test07();
//        List<String> strings = test07.restoreIpAddresses("25525511135");
//        List<String> strings = test07.restoreIpAddresses("0000");
//        List<String> strings = test07.restoreIpAddresses("101023");
        List<String> strings = test07.restoreIpAddresses("99999999999999999999");
        System.out.println(strings);
    }

    public List<String> restoreIpAddresses(String s) {
        List<String> res = new ArrayList<String>();
        backTracking(new StringBuilder(s), 0, 0, res);
        return res;
    }

    public void backTracking(StringBuilder sb, int startIndex, int pointNum, List<String> res) {
        if (pointNum == 3) {
            // 确认最后一段是否符合
            if (check(sb.substring(startIndex))) {
                res.add(sb.toString());
            }
            return;
        }
        for (int i = startIndex; i < sb.length(); i++) {
            if (check(sb.substring(startIndex, i + 1))) {
                sb.insert(i + 1, ".");
            } else {
                continue;
            }
            backTracking(sb, i + 2, pointNum + 1, res);
            sb.deleteCharAt(i + 1);
        }

    }

    /**
     * 检查是否符合要求
     *
     * @param s
     * @return
     */
    public boolean check(String s) {
        if (s.isEmpty()) {
            return false;
        }
        if (s.length() == 1 && s.charAt(0) == '0') {
            return true;
        }
        if (s.startsWith("0")) {
            return false;
        }
        if (s.length() > 3) {
            long l = Long.parseLong(s.substring(0, 4));
            if (l > 255) {
                return false;
            }
        }
        long l = Long.parseLong(s);
        if (l >= 0L && l <= 255L) {
            return true;
        }
        return false;
    }

}
